<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { itemFormSchema } from '../dict.data';
  import { saveOrUpdateDictItem } from '/@/api/system/dict/dict.api';

  export default defineComponent({
    name: 'DeptModal',
    components: { BasicModal, BasicForm },
    props: ['dictId'],
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const isUpdate = ref(true);

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        baseColProps: { span: 24 },
        schemas: itemFormSchema,
        showActionButtonGroup: false,
        mergeDynamicData: props,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() => '新增配置');

      async function handleSubmit() {
        try {
          const values = await validate();
          values.dictId = props.dictId;
          setModalProps({ confirmLoading: true });
          saveOrUpdateDictItem(values, unref(isUpdate));
          // TODO custom api
          // console.log(values, 'values');
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
